
<!doctype html>
<html lang="zh" class="no-js">
  <head>
    
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      
      
        <meta name="author" content="HENG">
      
      
      
        <link rel="prev" href="urls.html">
      
      
        <link rel="next" href="admin.html">
      
      
      <link rel="icon" href="assets/images/favicon.png">
      <meta name="generator" content="mkdocs-1.6.0, mkdocs-material-9.5.20">
    
    
      
        <title>视图 - Django杂记</title>
      
    
    
      <link rel="stylesheet" href="assets/stylesheets/main.66ac8b77.min.css">
      
        
        <link rel="stylesheet" href="assets/stylesheets/palette.06af60db.min.css">
      
      


    
    
      
    
    
      
        
        
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i%7CRoboto+Mono:400,400i,700,700i&display=fallback">
        <style>:root{--md-text-font:"Roboto";--md-code-font:"Roboto Mono"}</style>
      
    
    
    <script>__md_scope=new URL(".",location),__md_hash=e=>[...e].reduce((e,_)=>(e<<5)-e+_.charCodeAt(0),0),__md_get=(e,_=localStorage,t=__md_scope)=>JSON.parse(_.getItem(t.pathname+"."+e)),__md_set=(e,_,t=localStorage,a=__md_scope)=>{try{t.setItem(a.pathname+"."+e,JSON.stringify(_))}catch(e){}}</script>
    
      

    
    
    
  </head>
  
  
    
    
      
    
    
    
    
    <body dir="ltr" data-md-color-scheme="default" data-md-color-primary="deep-orange" data-md-color-accent="indigo">
  
    
    <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
    <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
    <label class="md-overlay" for="__drawer"></label>
    <div data-md-component="skip">
      
        
        <a href="#_1" class="md-skip">
          跳转至
        </a>
      
    </div>
    <div data-md-component="announce">
      
    </div>
    
    
      

  

<header class="md-header md-header--shadow" data-md-component="header">
  <nav class="md-header__inner md-grid" aria-label="页眉">
    <a href="index.html" title="Django杂记" class="md-header__button md-logo" aria-label="Django杂记" data-md-component="logo">
      
  
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54Z"/></svg>

    </a>
    <label class="md-header__button md-icon" for="__drawer">
      
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 6h18v2H3V6m0 5h18v2H3v-2m0 5h18v2H3v-2Z"/></svg>
    </label>
    <div class="md-header__title" data-md-component="header-title">
      <div class="md-header__ellipsis">
        <div class="md-header__topic">
          <span class="md-ellipsis">
            Django杂记
          </span>
        </div>
        <div class="md-header__topic" data-md-component="header-topic">
          <span class="md-ellipsis">
            
              视图
            
          </span>
        </div>
      </div>
    </div>
    
      
        <form class="md-header__option" data-md-component="palette">
  
    
    
    
    <input class="md-option" data-md-color-media="(prefers-color-scheme: light)" data-md-color-scheme="default" data-md-color-primary="deep-orange" data-md-color-accent="indigo"  aria-label="亮色模式"  type="radio" name="__palette" id="__palette_0">
    
      <label class="md-header__button md-icon" title="亮色模式" for="__palette_1" hidden>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a4 4 0 0 0-4 4 4 4 0 0 0 4 4 4 4 0 0 0 4-4 4 4 0 0 0-4-4m0 10a6 6 0 0 1-6-6 6 6 0 0 1 6-6 6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69Z"/></svg>
      </label>
    
  
    
    
    
    <input class="md-option" data-md-color-media="(prefers-color-scheme: dark)" data-md-color-scheme="slate" data-md-color-primary="indigo" data-md-color-accent="cyan"  aria-label="暗色模式"  type="radio" name="__palette" id="__palette_1">
    
      <label class="md-header__button md-icon" title="暗色模式" for="__palette_0" hidden>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12c0-2.42-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6a6 6 0 0 1 6 6 6 6 0 0 1-6 6m8-9.31V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69Z"/></svg>
      </label>
    
  
</form>
      
    
    
      <script>var media,input,key,value,palette=__md_get("__palette");if(palette&&palette.color){"(prefers-color-scheme)"===palette.color.media&&(media=matchMedia("(prefers-color-scheme: light)"),input=document.querySelector(media.matches?"[data-md-color-media='(prefers-color-scheme: light)']":"[data-md-color-media='(prefers-color-scheme: dark)']"),palette.color.media=input.getAttribute("data-md-color-media"),palette.color.scheme=input.getAttribute("data-md-color-scheme"),palette.color.primary=input.getAttribute("data-md-color-primary"),palette.color.accent=input.getAttribute("data-md-color-accent"));for([key,value]of Object.entries(palette.color))document.body.setAttribute("data-md-color-"+key,value)}</script>
    
    
    
      <label class="md-header__button md-icon" for="__search">
        
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5Z"/></svg>
      </label>
      <div class="md-search" data-md-component="search" role="dialog">
  <label class="md-search__overlay" for="__search"></label>
  <div class="md-search__inner" role="search">
    <form class="md-search__form" name="search">
      <input type="text" class="md-search__input" name="query" aria-label="搜索" placeholder="搜索" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="search-query" required>
      <label class="md-search__icon md-icon" for="__search">
        
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0 1 16 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 0 1 9.5 16 6.5 6.5 0 0 1 3 9.5 6.5 6.5 0 0 1 9.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5Z"/></svg>
        
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12Z"/></svg>
      </label>
      <nav class="md-search__options" aria-label="查找">
        
        <button type="reset" class="md-search__icon md-icon" title="清空当前内容" aria-label="清空当前内容" tabindex="-1">
          
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41Z"/></svg>
        </button>
      </nav>
      
    </form>
    <div class="md-search__output">
      <div class="md-search__scrollwrap" data-md-scrollfix>
        <div class="md-search-result" data-md-component="search-result">
          <div class="md-search-result__meta">
            正在初始化搜索引擎
          </div>
          <ol class="md-search-result__list" role="presentation"></ol>
        </div>
      </div>
    </div>
  </div>
</div>
    
    
      <div class="md-header__source">
        <a href="https://github.com/lmliheng/codes" title="前往仓库" class="md-source" data-md-component="source">
  <div class="md-source__icon md-icon">
    
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc.--><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg>
  </div>
  <div class="md-source__repository">
    Heng's Codes
  </div>
</a>
      </div>
    
  </nav>
  
</header>
    
    <div class="md-container" data-md-component="container">
      
      
        
          
        
      
      <main class="md-main" data-md-component="main">
        <div class="md-main__inner md-grid">
          
            
              
              <div class="md-sidebar md-sidebar--primary" data-md-component="sidebar" data-md-type="navigation" >
                <div class="md-sidebar__scrollwrap">
                  <div class="md-sidebar__inner">
                    



<nav class="md-nav md-nav--primary" aria-label="导航栏" data-md-level="0">
  <label class="md-nav__title" for="__drawer">
    <a href="index.html" title="Django杂记" class="md-nav__button md-logo" aria-label="Django杂记" data-md-component="logo">
      
  
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 8a3 3 0 0 0 3-3 3 3 0 0 0-3-3 3 3 0 0 0-3 3 3 3 0 0 0 3 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54Z"/></svg>

    </a>
    Django杂记
  </label>
  
    <div class="md-nav__source">
      <a href="https://github.com/lmliheng/codes" title="前往仓库" class="md-source" data-md-component="source">
  <div class="md-source__icon md-icon">
    
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc.--><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg>
  </div>
  <div class="md-source__repository">
    Heng's Codes
  </div>
</a>
    </div>
  
  <ul class="md-nav__list" data-md-scrollfix>
    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="index.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    主页
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="settings.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    配置文件
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="models.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    模型
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="urls.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    路由
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
    
  
  
  
    <li class="md-nav__item md-nav__item--active">
      
      <input class="md-nav__toggle md-toggle" type="checkbox" id="__toc">
      
      
        
      
      
        <label class="md-nav__link md-nav__link--active" for="__toc">
          
  
  <span class="md-ellipsis">
    视图
  </span>
  

          <span class="md-nav__icon md-icon"></span>
        </label>
      
      <a href="view.html" class="md-nav__link md-nav__link--active">
        
  
  <span class="md-ellipsis">
    视图
  </span>
  

      </a>
      
        

<nav class="md-nav md-nav--secondary" aria-label="目录">
  
  
  
    
  
  
    <label class="md-nav__title" for="__toc">
      <span class="md-nav__icon md-icon"></span>
      目录
    </label>
    <ul class="md-nav__list" data-md-component="toc" data-md-scrollfix>
      
        <li class="md-nav__item">
  <a href="#http" class="md-nav__link">
    <span class="md-ellipsis">
      HTTP响应返回字符串
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#render" class="md-nav__link">
    <span class="md-ellipsis">
      引入render函数
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_2" class="md-nav__link">
    <span class="md-ellipsis">
      返回错误
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_3" class="md-nav__link">
    <span class="md-ellipsis">
      重定向
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_4" class="md-nav__link">
    <span class="md-ellipsis">
      类视图
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_5" class="md-nav__link">
    <span class="md-ellipsis">
      视图装饰器
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#serve" class="md-nav__link">
    <span class="md-ellipsis">
      serve()视图
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#httprequest" class="md-nav__link">
    <span class="md-ellipsis">
      HttpRequest对象
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_6" class="md-nav__link">
    <span class="md-ellipsis">
      一、属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="一、属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestscheme" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.scheme
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestbody" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.body
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestpath" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.path
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4-httprequestpath_info" class="md-nav__link">
    <span class="md-ellipsis">
      4. HttpRequest.path_info
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#5-httprequestmethod" class="md-nav__link">
    <span class="md-ellipsis">
      5. HttpRequest.method
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#6-httprequestencoding" class="md-nav__link">
    <span class="md-ellipsis">
      6. HttpRequest.encoding
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#7-httprequestcontent_type" class="md-nav__link">
    <span class="md-ellipsis">
      7. HttpRequest.content_type
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#8-httprequestcontent_params" class="md-nav__link">
    <span class="md-ellipsis">
      8. HttpRequest.content_params
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#9-httprequestget" class="md-nav__link">
    <span class="md-ellipsis">
      9 HttpRequest.GET
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#10-httprequestpost" class="md-nav__link">
    <span class="md-ellipsis">
      10. HttpRequest.POST
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#11-httprequestcookies" class="md-nav__link">
    <span class="md-ellipsis">
      11. HttpRequest.COOKIES
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#12-httprequestfiles" class="md-nav__link">
    <span class="md-ellipsis">
      12. HttpRequest.FILES
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#13-httprequestmeta" class="md-nav__link">
    <span class="md-ellipsis">
      13. HttpRequest.META
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#13httprequestheaders" class="md-nav__link">
    <span class="md-ellipsis">
      13.HttpRequest.headers
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#14-httprequestresolver_match" class="md-nav__link">
    <span class="md-ellipsis">
      14. HttpRequest.resolver_match
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#app" class="md-nav__link">
    <span class="md-ellipsis">
      二、app带来的属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="二、app带来的属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestcurrent_app" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.current_app
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequesturlconf" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.urlconf
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestexception_reporter_filter" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.exception_reporter_filter
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4httprequestexception_reporter_class" class="md-nav__link">
    <span class="md-ellipsis">
      4.HttpRequest.exception_reporter_class
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_7" class="md-nav__link">
    <span class="md-ellipsis">
      三、中间件带来的属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="三、中间件带来的属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestsession" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.session
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestsite" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.site
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestuser" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.user
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_8" class="md-nav__link">
    <span class="md-ellipsis">
      四、方法
    </span>
  </a>
  
    <nav class="md-nav" aria-label="四、方法">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestget_host" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.get_host()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestget_port" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.get_port()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestget_full_path" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.get_full_path()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4-httprequestbuild_absolute_urilocation" class="md-nav__link">
    <span class="md-ellipsis">
      4. HttpRequest.build_absolute_uri(location)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#5-httprequestget_signed_cookiekey-defaultraise_error-salt-max_agenone" class="md-nav__link">
    <span class="md-ellipsis">
      5. HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#6-httprequestis_secure" class="md-nav__link">
    <span class="md-ellipsis">
      6. HttpRequest.is_secure()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#7-httprequestacceptsmime_type" class="md-nav__link">
    <span class="md-ellipsis">
      7. HttpRequest.accepts(mime_type)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#8-httprequestreadsizenone" class="md-nav__link">
    <span class="md-ellipsis">
      8. HttpRequest.read(size=None)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#9-httprequestreadline" class="md-nav__link">
    <span class="md-ellipsis">
      9. HttpRequest.readline()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#10-httprequestreadlines" class="md-nav__link">
    <span class="md-ellipsis">
      10. HttpRequest.readlines()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#11-httprequest__iter__" class="md-nav__link">
    <span class="md-ellipsis">
      11. HttpRequest.__iter__()
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
    </ul>
  
</nav>
      
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="admin.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    管理员
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="template.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    模板
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="static.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    静态资源
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="database.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    数据库
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="file.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    文件上传与生成
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="cron.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    定时任务
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="translator.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    流媒体
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="linux.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    部署笔记
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="codeplan.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    计划表项目搭建
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="fontend.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    前后端分离架构
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="question.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    常见问题
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="exe.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    应用程序
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="mkdocs.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    mkdocs笔记
  </span>
  

      </a>
    </li>
  

    
      
      
  
  
  
  
    <li class="md-nav__item">
      <a href="markdown.html" class="md-nav__link">
        
  
  <span class="md-ellipsis">
    Markdown格式
  </span>
  

      </a>
    </li>
  

    
  </ul>
</nav>
                  </div>
                </div>
              </div>
            
            
              
              <div class="md-sidebar md-sidebar--secondary" data-md-component="sidebar" data-md-type="toc" >
                <div class="md-sidebar__scrollwrap">
                  <div class="md-sidebar__inner">
                    

<nav class="md-nav md-nav--secondary" aria-label="目录">
  
  
  
    
  
  
    <label class="md-nav__title" for="__toc">
      <span class="md-nav__icon md-icon"></span>
      目录
    </label>
    <ul class="md-nav__list" data-md-component="toc" data-md-scrollfix>
      
        <li class="md-nav__item">
  <a href="#http" class="md-nav__link">
    <span class="md-ellipsis">
      HTTP响应返回字符串
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#render" class="md-nav__link">
    <span class="md-ellipsis">
      引入render函数
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_2" class="md-nav__link">
    <span class="md-ellipsis">
      返回错误
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_3" class="md-nav__link">
    <span class="md-ellipsis">
      重定向
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_4" class="md-nav__link">
    <span class="md-ellipsis">
      类视图
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_5" class="md-nav__link">
    <span class="md-ellipsis">
      视图装饰器
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#serve" class="md-nav__link">
    <span class="md-ellipsis">
      serve()视图
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#httprequest" class="md-nav__link">
    <span class="md-ellipsis">
      HttpRequest对象
    </span>
  </a>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_6" class="md-nav__link">
    <span class="md-ellipsis">
      一、属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="一、属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestscheme" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.scheme
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestbody" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.body
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestpath" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.path
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4-httprequestpath_info" class="md-nav__link">
    <span class="md-ellipsis">
      4. HttpRequest.path_info
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#5-httprequestmethod" class="md-nav__link">
    <span class="md-ellipsis">
      5. HttpRequest.method
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#6-httprequestencoding" class="md-nav__link">
    <span class="md-ellipsis">
      6. HttpRequest.encoding
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#7-httprequestcontent_type" class="md-nav__link">
    <span class="md-ellipsis">
      7. HttpRequest.content_type
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#8-httprequestcontent_params" class="md-nav__link">
    <span class="md-ellipsis">
      8. HttpRequest.content_params
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#9-httprequestget" class="md-nav__link">
    <span class="md-ellipsis">
      9 HttpRequest.GET
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#10-httprequestpost" class="md-nav__link">
    <span class="md-ellipsis">
      10. HttpRequest.POST
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#11-httprequestcookies" class="md-nav__link">
    <span class="md-ellipsis">
      11. HttpRequest.COOKIES
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#12-httprequestfiles" class="md-nav__link">
    <span class="md-ellipsis">
      12. HttpRequest.FILES
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#13-httprequestmeta" class="md-nav__link">
    <span class="md-ellipsis">
      13. HttpRequest.META
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#13httprequestheaders" class="md-nav__link">
    <span class="md-ellipsis">
      13.HttpRequest.headers
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#14-httprequestresolver_match" class="md-nav__link">
    <span class="md-ellipsis">
      14. HttpRequest.resolver_match
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#app" class="md-nav__link">
    <span class="md-ellipsis">
      二、app带来的属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="二、app带来的属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestcurrent_app" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.current_app
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequesturlconf" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.urlconf
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestexception_reporter_filter" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.exception_reporter_filter
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4httprequestexception_reporter_class" class="md-nav__link">
    <span class="md-ellipsis">
      4.HttpRequest.exception_reporter_class
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_7" class="md-nav__link">
    <span class="md-ellipsis">
      三、中间件带来的属性
    </span>
  </a>
  
    <nav class="md-nav" aria-label="三、中间件带来的属性">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestsession" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.session
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestsite" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.site
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestuser" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.user
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
        <li class="md-nav__item">
  <a href="#_8" class="md-nav__link">
    <span class="md-ellipsis">
      四、方法
    </span>
  </a>
  
    <nav class="md-nav" aria-label="四、方法">
      <ul class="md-nav__list">
        
          <li class="md-nav__item">
  <a href="#1-httprequestget_host" class="md-nav__link">
    <span class="md-ellipsis">
      1. HttpRequest.get_host()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#2-httprequestget_port" class="md-nav__link">
    <span class="md-ellipsis">
      2. HttpRequest.get_port()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#3-httprequestget_full_path" class="md-nav__link">
    <span class="md-ellipsis">
      3. HttpRequest.get_full_path()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#4-httprequestbuild_absolute_urilocation" class="md-nav__link">
    <span class="md-ellipsis">
      4. HttpRequest.build_absolute_uri(location)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#5-httprequestget_signed_cookiekey-defaultraise_error-salt-max_agenone" class="md-nav__link">
    <span class="md-ellipsis">
      5. HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#6-httprequestis_secure" class="md-nav__link">
    <span class="md-ellipsis">
      6. HttpRequest.is_secure()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#7-httprequestacceptsmime_type" class="md-nav__link">
    <span class="md-ellipsis">
      7. HttpRequest.accepts(mime_type)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#8-httprequestreadsizenone" class="md-nav__link">
    <span class="md-ellipsis">
      8. HttpRequest.read(size=None)
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#9-httprequestreadline" class="md-nav__link">
    <span class="md-ellipsis">
      9. HttpRequest.readline()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#10-httprequestreadlines" class="md-nav__link">
    <span class="md-ellipsis">
      10. HttpRequest.readlines()
    </span>
  </a>
  
</li>
        
          <li class="md-nav__item">
  <a href="#11-httprequest__iter__" class="md-nav__link">
    <span class="md-ellipsis">
      11. HttpRequest.__iter__()
    </span>
  </a>
  
</li>
        
      </ul>
    </nav>
  
</li>
      
    </ul>
  
</nav>
                  </div>
                </div>
              </div>
            
          
          
            <div class="md-content" data-md-component="content">
              <article class="md-content__inner md-typeset">
                
                  

  
  


<h1 id="_1">视图</h1>
<p>Django的视图层包含下面一些主要内容：
 <code>URL路由
视图函数
快捷方式
装饰器
请求与响应
类视图
文件上传
CSV/PDF生成
内置中间件
 <div class="language-text highlight"><pre><span></span><code><span id="__span-0-1"><a id="__codelineno-0-1" name="__codelineno-0-1" href="#__codelineno-0-1"></a>
</span></code></pre></div>
 Django的视图类型可以分为函数视图和类视图，也就是FBV和CBV。
 大多数场景下，函数视图更简单易懂，代码量更少。
 但是在需要继承、封装某些视图的时候，CBV就能发挥优势。</code></p>
<h3 id="http">HTTP响应返回字符串</h3>
<div class="language-python highlight"><pre><span></span><code><span id="__span-1-1"><a id="__codelineno-1-1" name="__codelineno-1-1" href="#__codelineno-1-1"></a><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
</span><span id="__span-1-2"><a id="__codelineno-1-2" name="__codelineno-1-2" href="#__codelineno-1-2"></a>
</span><span id="__span-1-3"><a id="__codelineno-1-3" name="__codelineno-1-3" href="#__codelineno-1-3"></a><span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
</span><span id="__span-1-4"><a id="__codelineno-1-4" name="__codelineno-1-4" href="#__codelineno-1-4"></a>    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;Hello, World!&quot;</span><span class="p">)</span>
</span></code></pre></div>
<h3 id="render">引入render函数</h3>
<p>render函数来自django.shortcuts
<div class="language-text highlight"><pre><span></span><code><span id="__span-2-1"><a id="__codelineno-2-1" name="__codelineno-2-1" href="#__codelineno-2-1"></a>from django.shortcuts import render
</span><span id="__span-2-2"><a id="__codelineno-2-2" name="__codelineno-2-2" href="#__codelineno-2-2"></a>
</span><span id="__span-2-3"><a id="__codelineno-2-3" name="__codelineno-2-3" href="#__codelineno-2-3"></a>from .models import Question
</span><span id="__span-2-4"><a id="__codelineno-2-4" name="__codelineno-2-4" href="#__codelineno-2-4"></a>
</span><span id="__span-2-5"><a id="__codelineno-2-5" name="__codelineno-2-5" href="#__codelineno-2-5"></a>
</span><span id="__span-2-6"><a id="__codelineno-2-6" name="__codelineno-2-6" href="#__codelineno-2-6"></a>def index(request):
</span><span id="__span-2-7"><a id="__codelineno-2-7" name="__codelineno-2-7" href="#__codelineno-2-7"></a>    latest_question_list = Question.objects.order_by(&#39;-pub_date&#39;)[:5]
</span><span id="__span-2-8"><a id="__codelineno-2-8" name="__codelineno-2-8" href="#__codelineno-2-8"></a>    context = {&#39;latest_question_list&#39;: latest_question_list}
</span><span id="__span-2-9"><a id="__codelineno-2-9" name="__codelineno-2-9" href="#__codelineno-2-9"></a>    return render(request, &#39;polls/index.html&#39;, context)
</span></code></pre></div></p>
<h3 id="_2">返回错误</h3>
<p><div class="language-text highlight"><pre><span></span><code><span id="__span-3-1"><a id="__codelineno-3-1" name="__codelineno-3-1" href="#__codelineno-3-1"></a>from django.http import HttpResponse, HttpResponseNotFound
</span><span id="__span-3-2"><a id="__codelineno-3-2" name="__codelineno-3-2" href="#__codelineno-3-2"></a>
</span><span id="__span-3-3"><a id="__codelineno-3-3" name="__codelineno-3-3" href="#__codelineno-3-3"></a>def my_view(request):
</span><span id="__span-3-4"><a id="__codelineno-3-4" name="__codelineno-3-4" href="#__codelineno-3-4"></a>    # ...
</span><span id="__span-3-5"><a id="__codelineno-3-5" name="__codelineno-3-5" href="#__codelineno-3-5"></a>    if foo:
</span><span id="__span-3-6"><a id="__codelineno-3-6" name="__codelineno-3-6" href="#__codelineno-3-6"></a>        return HttpResponseNotFound(&#39;&lt;h1&gt;Page not found&lt;/h1&gt;&#39;)
</span><span id="__span-3-7"><a id="__codelineno-3-7" name="__codelineno-3-7" href="#__codelineno-3-7"></a>    else:
</span><span id="__span-3-8"><a id="__codelineno-3-8" name="__codelineno-3-8" href="#__codelineno-3-8"></a>        return HttpResponse(&#39;&lt;h1&gt;Page was found&lt;/h1&gt;&#39;)
</span></code></pre></div>
<div class="language-text highlight"><pre><span></span><code><span id="__span-4-1"><a id="__codelineno-4-1" name="__codelineno-4-1" href="#__codelineno-4-1"></a>from django.http import HttpResponse
</span><span id="__span-4-2"><a id="__codelineno-4-2" name="__codelineno-4-2" href="#__codelineno-4-2"></a>
</span><span id="__span-4-3"><a id="__codelineno-4-3" name="__codelineno-4-3" href="#__codelineno-4-3"></a>def my_view(request):
</span><span id="__span-4-4"><a id="__codelineno-4-4" name="__codelineno-4-4" href="#__codelineno-4-4"></a>    # ...
</span><span id="__span-4-5"><a id="__codelineno-4-5" name="__codelineno-4-5" href="#__codelineno-4-5"></a>
</span><span id="__span-4-6"><a id="__codelineno-4-6" name="__codelineno-4-6" href="#__codelineno-4-6"></a>    # Return a &quot;created&quot; (201) response code.
</span><span id="__span-4-7"><a id="__codelineno-4-7" name="__codelineno-4-7" href="#__codelineno-4-7"></a>    return HttpResponse(status=201)
</span></code></pre></div>
三、Http404异常
class django.http.Http404</p>
<p>当你返回错误，例如 HttpResponseNotFound ，你需要定义错误页面的 HTML 。</p>
<p><code>return HttpResponseNotFound('&lt;h1&gt;Page not found&lt;/h1&gt;')</code>
为了方便，Django 内置了 Http404 异常。（没有Http400、Http403等，只有这一个）</p>
<p>如果你在视图的任何地方引发了 Http404 ，Django 会捕捉到它并且返回标准的错误页面，连同 HTTP 错误代码 404 。
<div class="language-text highlight"><pre><span></span><code><span id="__span-5-1"><a id="__codelineno-5-1" name="__codelineno-5-1" href="#__codelineno-5-1"></a>from django.http import Http404
</span><span id="__span-5-2"><a id="__codelineno-5-2" name="__codelineno-5-2" href="#__codelineno-5-2"></a>from django.shortcuts import render
</span><span id="__span-5-3"><a id="__codelineno-5-3" name="__codelineno-5-3" href="#__codelineno-5-3"></a>from polls.models import Poll
</span><span id="__span-5-4"><a id="__codelineno-5-4" name="__codelineno-5-4" href="#__codelineno-5-4"></a>
</span><span id="__span-5-5"><a id="__codelineno-5-5" name="__codelineno-5-5" href="#__codelineno-5-5"></a>def detail(request, poll_id):
</span><span id="__span-5-6"><a id="__codelineno-5-6" name="__codelineno-5-6" href="#__codelineno-5-6"></a>    try:
</span><span id="__span-5-7"><a id="__codelineno-5-7" name="__codelineno-5-7" href="#__codelineno-5-7"></a>        p = Poll.objects.get(pk=poll_id)
</span><span id="__span-5-8"><a id="__codelineno-5-8" name="__codelineno-5-8" href="#__codelineno-5-8"></a>    except Poll.DoesNotExist:
</span><span id="__span-5-9"><a id="__codelineno-5-9" name="__codelineno-5-9" href="#__codelineno-5-9"></a>        raise Http404(&quot;Poll does not exist&quot;)  # 注意是raise，不是return
</span><span id="__span-5-10"><a id="__codelineno-5-10" name="__codelineno-5-10" href="#__codelineno-5-10"></a>    return render(request, &#39;polls/detail.html&#39;, {&#39;poll&#39;: p})
</span></code></pre></div>
为了在Django返回404时显示自定义的HTML，可以创建一个名为404.html的HTML模板，并将其放置在模板树的顶层。</p>
<p>只有当DEBUG设置为False时，此模板才会被自动使用。DEBUG为True表示开发模式，Django会展示详细的错误信息页面，而不是针对性的404页面。</p>
<p>实际上，当你raise了Http404后：</p>
<p>Django会首先读取django.conf.urls.handler404的值，默认为django.views.defaults.page_not_found()视图
执行page_not_found()视图
判断是否自定义了404.html，如果有，输出该HTML文件
如果没有，输出默认的404提示信息
上面的流程就给我们留下了两个自定义404页面的钩子：</p>
<p>第一个是在urls中重新指定handler404的值，也就是用哪个视图来处理404
第二个是在page_not_found视图中，使用自定义的404.html
一个是自定义处理视图，一个是自定义展示的404页面。</p>
<p>自定义的404.html页面应当位于模板引擎可以搜索到的路径。            </p>
<h3 id="_3">重定向</h3>
<p><div class="language-text highlight"><pre><span></span><code><span id="__span-6-1"><a id="__codelineno-6-1" name="__codelineno-6-1" href="#__codelineno-6-1"></a> return HttpResponseRedirect(reverse(&#39;polls:results&#39;, args=(question.id,)))
</span></code></pre></div>
返回的是一个HttpResponseRedirect而不是先前我们常用的HttpResponse。HttpResponseRedirect需要一个参数：重定向的URL。这里有一个建议，当你成功处理POST数据后，应当保持一个良好的习惯，始终返回一个HttpResponseRedirect。这不仅仅是对Django而言，它是一个良好的WEB开发习惯。
参数to可以是：</p>
<p>一个模型实例：将调用模型的get_absolute_url()函数，反向解析出目的url；
URL的name名称：可能带有参数：reverse()将用于反向解析url；
一个绝对的或相对的URL：将原封不动的作为重定向的目标位置。
默认情况下是临时重定向，如果设置permanent=True将永久重定向。
 ```
 redirect()
redirect(to, args, permanent=False, *kwargs)</p>
<p>根据传递进来的url参数，返回HttpResponseRedirect。</p>
<p>参数to可以是：</p>
<p>一个模型实例：将调用模型的get_absolute_url()函数，反向解析出目的url；
URL的name名称：可能带有参数：reverse()将用于反向解析url；
一个绝对的或相对的URL：将原封不动的作为重定向的目标位置。
默认情况下是临时重定向，如果设置permanent=True将永久重定向。</p>
<p>范例：</p>
<p>1.调用对象的get_absolute_url()方法来重定向URL：
<div class="language-text highlight"><pre><span></span><code><span id="__span-7-1"><a id="__codelineno-7-1" name="__codelineno-7-1" href="#__codelineno-7-1"></a>from django.shortcuts import redirect
</span><span id="__span-7-2"><a id="__codelineno-7-2" name="__codelineno-7-2" href="#__codelineno-7-2"></a>
</span><span id="__span-7-3"><a id="__codelineno-7-3" name="__codelineno-7-3" href="#__codelineno-7-3"></a>def my_view(request):
</span><span id="__span-7-4"><a id="__codelineno-7-4" name="__codelineno-7-4" href="#__codelineno-7-4"></a>    ...
</span><span id="__span-7-5"><a id="__codelineno-7-5" name="__codelineno-7-5" href="#__codelineno-7-5"></a>    obj = MyModel.objects.get(...)
</span><span id="__span-7-6"><a id="__codelineno-7-6" name="__codelineno-7-6" href="#__codelineno-7-6"></a>    return redirect(obj)
</span></code></pre></div>
2.传递URL的name名称，内部会自动使用reverse()方法反向解析url：
<div class="language-text highlight"><pre><span></span><code><span id="__span-8-1"><a id="__codelineno-8-1" name="__codelineno-8-1" href="#__codelineno-8-1"></a>def my_view(request):
</span><span id="__span-8-2"><a id="__codelineno-8-2" name="__codelineno-8-2" href="#__codelineno-8-2"></a>    ...
</span><span id="__span-8-3"><a id="__codelineno-8-3" name="__codelineno-8-3" href="#__codelineno-8-3"></a>    return redirect(&#39;some-view-name&#39;, foo=&#39;bar&#39;)
</span></code></pre></div>
重定向到硬编码的URL：
<div class="language-text highlight"><pre><span></span><code><span id="__span-9-1"><a id="__codelineno-9-1" name="__codelineno-9-1" href="#__codelineno-9-1"></a>def my_view(request):
</span><span id="__span-9-2"><a id="__codelineno-9-2" name="__codelineno-9-2" href="#__codelineno-9-2"></a>    ...
</span><span id="__span-9-3"><a id="__codelineno-9-3" name="__codelineno-9-3" href="#__codelineno-9-3"></a>    return redirect(&#39;/some/url/&#39;)
</span></code></pre></div>
重定向到一个完整的URL：
<div class="language-text highlight"><pre><span></span><code><span id="__span-10-1"><a id="__codelineno-10-1" name="__codelineno-10-1" href="#__codelineno-10-1"></a>def my_view(request):
</span><span id="__span-10-2"><a id="__codelineno-10-2" name="__codelineno-10-2" href="#__codelineno-10-2"></a>    ...
</span><span id="__span-10-3"><a id="__codelineno-10-3" name="__codelineno-10-3" href="#__codelineno-10-3"></a>    return redirect(&#39;https://www.liujiangblog.com/&#39;)
</span><span id="__span-10-4"><a id="__codelineno-10-4" name="__codelineno-10-4" href="#__codelineno-10-4"></a>
</span><span id="__span-10-5"><a id="__codelineno-10-5" name="__codelineno-10-5" href="#__codelineno-10-5"></a>#或者
</span><span id="__span-10-6"><a id="__codelineno-10-6" name="__codelineno-10-6" href="#__codelineno-10-6"></a>def my_view(request):
</span><span id="__span-10-7"><a id="__codelineno-10-7" name="__codelineno-10-7" href="#__codelineno-10-7"></a>    ...
</span><span id="__span-10-8"><a id="__codelineno-10-8" name="__codelineno-10-8" href="#__codelineno-10-8"></a>    return redirect(&#39;/some/url/&#39;)
</span></code></pre></div>
所有上述形式都接受permanent参数，如果设置为True，将返回永久重定向：
<div class="language-text highlight"><pre><span></span><code><span id="__span-11-1"><a id="__codelineno-11-1" name="__codelineno-11-1" href="#__codelineno-11-1"></a>def my_view(request):
</span><span id="__span-11-2"><a id="__codelineno-11-2" name="__codelineno-11-2" href="#__codelineno-11-2"></a>    ...
</span><span id="__span-11-3"><a id="__codelineno-11-3" name="__codelineno-11-3" href="#__codelineno-11-3"></a>    obj = MyModel.objects.get(...)
</span><span id="__span-11-4"><a id="__codelineno-11-4" name="__codelineno-11-4" href="#__codelineno-11-4"></a>    return redirect(obj, permanent=True)
</span></code></pre></div></p>
<h3 id="_4">类视图</h3>
<p>如下例：</p>
<p><strong>app/urls.py</strong>
<div class="language-python highlight"><pre><span></span><code><span id="__span-12-1"><a id="__codelineno-12-1" name="__codelineno-12-1" href="#__codelineno-12-1"></a><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">path</span>
</span><span id="__span-12-2"><a id="__codelineno-12-2" name="__codelineno-12-2" href="#__codelineno-12-2"></a>
</span><span id="__span-12-3"><a id="__codelineno-12-3" name="__codelineno-12-3" href="#__codelineno-12-3"></a><span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">views</span>
</span><span id="__span-12-4"><a id="__codelineno-12-4" name="__codelineno-12-4" href="#__codelineno-12-4"></a>
</span><span id="__span-12-5"><a id="__codelineno-12-5" name="__codelineno-12-5" href="#__codelineno-12-5"></a><span class="n">app_name</span> <span class="o">=</span> <span class="s1">&#39;polls&#39;</span>
</span><span id="__span-12-6"><a id="__codelineno-12-6" name="__codelineno-12-6" href="#__codelineno-12-6"></a><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
</span><span id="__span-12-7"><a id="__codelineno-12-7" name="__codelineno-12-7" href="#__codelineno-12-7"></a>    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">IndexView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;index&#39;</span><span class="p">),</span>
</span><span id="__span-12-8"><a id="__codelineno-12-8" name="__codelineno-12-8" href="#__codelineno-12-8"></a>    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;&lt;int:pk&gt;/&#39;</span><span class="p">,</span> <span class="n">views</span><span class="o">.</span><span class="n">DetailView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;detail&#39;</span><span class="p">),</span>
</span><span id="__span-12-9"><a id="__codelineno-12-9" name="__codelineno-12-9" href="#__codelineno-12-9"></a><span class="p">]</span>
</span></code></pre></div>
<strong>app/views.py</strong>
<div class="language-python highlight"><pre><span></span><code><span id="__span-13-1"><a id="__codelineno-13-1" name="__codelineno-13-1" href="#__codelineno-13-1"></a><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponseRedirect</span>
</span><span id="__span-13-2"><a id="__codelineno-13-2" name="__codelineno-13-2" href="#__codelineno-13-2"></a><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">get_object_or_404</span><span class="p">,</span> <span class="n">render</span>
</span><span id="__span-13-3"><a id="__codelineno-13-3" name="__codelineno-13-3" href="#__codelineno-13-3"></a><span class="kn">from</span> <span class="nn">django.urls</span> <span class="kn">import</span> <span class="n">reverse</span>
</span><span id="__span-13-4"><a id="__codelineno-13-4" name="__codelineno-13-4" href="#__codelineno-13-4"></a><span class="kn">from</span> <span class="nn">django.views</span> <span class="kn">import</span> <span class="n">generic</span>
</span><span id="__span-13-5"><a id="__codelineno-13-5" name="__codelineno-13-5" href="#__codelineno-13-5"></a>
</span><span id="__span-13-6"><a id="__codelineno-13-6" name="__codelineno-13-6" href="#__codelineno-13-6"></a><span class="kn">from</span> <span class="nn">.models</span> <span class="kn">import</span> <span class="n">Choice</span><span class="p">,</span> <span class="n">Question</span>
</span><span id="__span-13-7"><a id="__codelineno-13-7" name="__codelineno-13-7" href="#__codelineno-13-7"></a>
</span><span id="__span-13-8"><a id="__codelineno-13-8" name="__codelineno-13-8" href="#__codelineno-13-8"></a>
</span><span id="__span-13-9"><a id="__codelineno-13-9" name="__codelineno-13-9" href="#__codelineno-13-9"></a><span class="k">class</span> <span class="nc">IndexView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">ListView</span><span class="p">):</span>
</span><span id="__span-13-10"><a id="__codelineno-13-10" name="__codelineno-13-10" href="#__codelineno-13-10"></a>    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/index.html&#39;</span>
</span><span id="__span-13-11"><a id="__codelineno-13-11" name="__codelineno-13-11" href="#__codelineno-13-11"></a>    <span class="n">context_object_name</span> <span class="o">=</span> <span class="s1">&#39;latest_question_list&#39;</span>
</span><span id="__span-13-12"><a id="__codelineno-13-12" name="__codelineno-13-12" href="#__codelineno-13-12"></a>
</span><span id="__span-13-13"><a id="__codelineno-13-13" name="__codelineno-13-13" href="#__codelineno-13-13"></a>    <span class="k">def</span> <span class="nf">get_queryset</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
</span><span id="__span-13-14"><a id="__codelineno-13-14" name="__codelineno-13-14" href="#__codelineno-13-14"></a><span class="w">        </span><span class="sd">&quot;&quot;&quot;Return the last five published questions.&quot;&quot;&quot;</span>
</span><span id="__span-13-15"><a id="__codelineno-13-15" name="__codelineno-13-15" href="#__codelineno-13-15"></a>        <span class="k">return</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-pub_date&#39;</span><span class="p">)[:</span><span class="mi">5</span><span class="p">]</span>
</span><span id="__span-13-16"><a id="__codelineno-13-16" name="__codelineno-13-16" href="#__codelineno-13-16"></a>
</span><span id="__span-13-17"><a id="__codelineno-13-17" name="__codelineno-13-17" href="#__codelineno-13-17"></a>
</span><span id="__span-13-18"><a id="__codelineno-13-18" name="__codelineno-13-18" href="#__codelineno-13-18"></a><span class="k">class</span> <span class="nc">DetailView</span><span class="p">(</span><span class="n">generic</span><span class="o">.</span><span class="n">DetailView</span><span class="p">):</span>
</span><span id="__span-13-19"><a id="__codelineno-13-19" name="__codelineno-13-19" href="#__codelineno-13-19"></a>    <span class="n">model</span> <span class="o">=</span> <span class="n">Question</span>
</span><span id="__span-13-20"><a id="__codelineno-13-20" name="__codelineno-13-20" href="#__codelineno-13-20"></a>    <span class="n">template_name</span> <span class="o">=</span> <span class="s1">&#39;polls/detail.html&#39;</span>
</span></code></pre></div></p>
<h3 id="_5">视图装饰器</h3>
<p>Django内置了一些装饰器，用来对视图函数进行一些控制。
<div class="language-text highlight"><pre><span></span><code><span id="__span-14-1"><a id="__codelineno-14-1" name="__codelineno-14-1" href="#__codelineno-14-1"></a>require_http_methods()
</span></code></pre></div>
此装饰器位于 django.views.decorators.http模块，用于限制可以访问该视图的HTTP方法。</p>
<p>如果请求的HTTP方法，不是指定的方法之一，则返回django.http.HttpResponseNotAllowed响应。</p>
<p>看例子：</p>
<p><div class="language-text highlight"><pre><span></span><code><span id="__span-15-1"><a id="__codelineno-15-1" name="__codelineno-15-1" href="#__codelineno-15-1"></a>from django.views.decorators.http import require_http_methods
</span><span id="__span-15-2"><a id="__codelineno-15-2" name="__codelineno-15-2" href="#__codelineno-15-2"></a>
</span><span id="__span-15-3"><a id="__codelineno-15-3" name="__codelineno-15-3" href="#__codelineno-15-3"></a>@require_http_methods([&quot;GET&quot;, &quot;POST&quot;])             # 注意参数的提供方式
</span><span id="__span-15-4"><a id="__codelineno-15-4" name="__codelineno-15-4" href="#__codelineno-15-4"></a>def my_view(request):
</span><span id="__span-15-5"><a id="__codelineno-15-5" name="__codelineno-15-5" href="#__codelineno-15-5"></a>    # 我们决定只有GET或者POST请求可以访问这个视图
</span><span id="__span-15-6"><a id="__codelineno-15-6" name="__codelineno-15-6" href="#__codelineno-15-6"></a>    # ...
</span><span id="__span-15-7"><a id="__codelineno-15-7" name="__codelineno-15-7" href="#__codelineno-15-7"></a>    pass
</span></code></pre></div>
参数必须是大写字符串。</p>
<p>require_GET()
上面的狭隘版本，只允许GET请求访问。位于 django.views.decorators.http模块。</p>
<p>require_POST()
只允许POST请求访问。位于 django.views.decorators.http模块。</p>
<p>require_safe()
只允许安全的请求类型，也就是GET和HEAD访问。位于 django.views.decorators.http模块。</p>
<p>gzip_page()
对视图的响应内容进行压缩，如果浏览器支持。位于 django.views.decorators.gzip模块。</p>
<p>更多的装饰器如下所示，有兴趣的可以自行研究：</p>
<p>condition(etag_func=None, last_modified_func=None)
etag(etag_func)
last_modified(last_modified_func)
vary_on_cookie(func)
vary_on_headers(*headers)
cache_control()
never_cache(view_func)</p>
<h3 id="serve">serve()视图</h3>
<p>Django开发过程中，出了Python代码、前端静态文件，还有一类媒体文件，比如用户上传的图片、文件等等，统称为MEDIA。</p>
<p>这些MEDIA都是有用的资源，我们往往希望根据某个URL，从浏览器上直接获取它们，比如：</p>
<p>访问https://www.liujiangblog.com/logo.jpg，浏览器会显示logo图片
访问https://www.liujiangblog.com/document.doc，浏览器会自动下载document文档
这些功能，一般都是在代码上线后，通过类似Ngnix的Web服务器代理实现的。</p>
<p>为了方便在开发过程中，对MEDIA资源的使用和测试，Django内置了一个serve()视图，帮我们实现了同样的功能。</p>
<p>但是要谨记：serve()视图只能用于开发环境！</p>
<p>使用步骤：</p>
<p>首先，在根路由urls中添加下面的代码：
<div class="language-text highlight"><pre><span></span><code><span id="__span-16-1"><a id="__codelineno-16-1" name="__codelineno-16-1" href="#__codelineno-16-1"></a>from django.conf import settings
</span><span id="__span-16-2"><a id="__codelineno-16-2" name="__codelineno-16-2" href="#__codelineno-16-2"></a>from django.urls import re_path
</span><span id="__span-16-3"><a id="__codelineno-16-3" name="__codelineno-16-3" href="#__codelineno-16-3"></a>from django.views.static import serve              # 以上三个导入不能忘
</span><span id="__span-16-4"><a id="__codelineno-16-4" name="__codelineno-16-4" href="#__codelineno-16-4"></a>
</span><span id="__span-16-5"><a id="__codelineno-16-5" name="__codelineno-16-5" href="#__codelineno-16-5"></a># ... 你原来的URLconf放这里...
</span><span id="__span-16-6"><a id="__codelineno-16-6" name="__codelineno-16-6" href="#__codelineno-16-6"></a>
</span><span id="__span-16-7"><a id="__codelineno-16-7" name="__codelineno-16-7" href="#__codelineno-16-7"></a>if settings.DEBUG:
</span><span id="__span-16-8"><a id="__codelineno-16-8" name="__codelineno-16-8" href="#__codelineno-16-8"></a>    urlpatterns += [
</span><span id="__span-16-9"><a id="__codelineno-16-9" name="__codelineno-16-9" href="#__codelineno-16-9"></a>        re_path(r&#39;^media/(?P&lt;path&gt;.*)$&#39;, serve, {
</span><span id="__span-16-10"><a id="__codelineno-16-10" name="__codelineno-16-10" href="#__codelineno-16-10"></a>            &#39;document_root&#39;: settings.MEDIA_ROOT,
</span><span id="__span-16-11"><a id="__codelineno-16-11" name="__codelineno-16-11" href="#__codelineno-16-11"></a>        }),
</span><span id="__span-16-12"><a id="__codelineno-16-12" name="__codelineno-16-12" href="#__codelineno-16-12"></a>    ]
</span><span id="__span-16-13"><a id="__codelineno-16-13" name="__codelineno-16-13" href="#__codelineno-16-13"></a>然后：
</span></code></pre></div>
确认settings.DEBUG配置项为True，也就是出于开发模式
在settings中添加下面的配置
<div class="language-text highlight"><pre><span></span><code><span id="__span-17-1"><a id="__codelineno-17-1" name="__codelineno-17-1" href="#__codelineno-17-1"></a>MEDIA_URL = &#39;/media/&#39;
</span><span id="__span-17-2"><a id="__codelineno-17-2" name="__codelineno-17-2" href="#__codelineno-17-2"></a>MEDIA_ROOT = &#39;/media/&#39;
</span></code></pre></div>
如果是windows操作系统，在你的Django项目所在的盘符的根目录下，新建一个media文件夹，将你的MEDIA资源全部拷贝进去，比如c:\media或者d:\media等等。
启动开发服务器
访问类似127.0.0.1:8000/media/logo.jpg的地址可以看到图片
访问类似127.0.0.1:8000/media/blog.md的地址会自动下载blog.md文件</p>
<h2 id="httprequest">HttpRequest对象</h2>
<p>每当一个用户请求发送过来，Django将HTTP数据包中的相关内容，打包成为一个HttpRequest对象，并传递给视图函数作为第一位置参数，也就是request，供我们调用。</p>
<p>HttpRequest对象中包含了非常多的重要的信息和数据，应该熟练掌握它。</p>
<p>所有的请求和响应对象都位于<code>django.http</code>模块内。</p>
<h2 id="_6">一、属性</h2>
<p>HttpRequest对象的大部分属性是只读的，除非特别注明。</p>
<h4 id="1-httprequestscheme">1. HttpRequest.scheme</h4>
<p>字符串类型，表示请求的协议种类，'http'或'https'。</p>
<h4 id="2-httprequestbody">2. HttpRequest.body</h4>
<p>bytes类型，表示原始HTTP请求的正文。它对于处理非HTML形式的数据非常有用：二进制图像、XML等。如果要处理常规的表单数据，应该使用<code>HttpRequest.POST</code>。</p>
<p>还可以使用类似读写文件的方式从HttpRequest中读取数据，参见HttpRequest.read()。</p>
<h3 id="3-httprequestpath">3. HttpRequest.path</h3>
<p>字符串类型，表示当前请求页面的完整路径，但是不包括协议名和域名。例如："/music/bands/the_beatles/"。</p>
<p>这个属性，常被用于我们进行某项操作时，如果不通过，返回用户先前浏览的页面。非常有用！</p>
<h3 id="4-httprequestpath_info">4. HttpRequest.path_info</h3>
<p>在某些Web服务器配置下，主机名后的URL部分被分成脚本前缀部分和路径信息部分。<code>path_info</code> 属性将始终包含路径信息部分，不论使用的Web服务器是什么。使用它代替path可以让代码在测试和开发环境中更容易地切换。</p>
<p>例如，如果应用的WSGIScriptAlias设置为<code>/minfo</code>，那么<code>HttpRequest.path</code>等于<code>/music/bands/the_beatles/</code> ，而<code>HttpRequest.path_info</code>为<code>/minfo/music/bands/the_beatles/</code>。</p>
<h3 id="5-httprequestmethod">5. HttpRequest.method</h3>
<p>字符串类型，表示请求使用的HTTP方法。默认为大写。 像这样：</p>
<p>if request.method == 'GET':
    do_something()
elif request.method == 'POST':
    do_something_else()</p>
<p>通过这个属性来判断请求的方法，然后根据请求的方法不同，在视图中执行不同的代码。</p>
<h3 id="6-httprequestencoding">6. HttpRequest.encoding</h3>
<p>字符串类型，表示提交的数据的编码方式（如果为None 则表示使用<code>DEFAULT_CHARSET</code>设置）。 这个属性是可写的，可以通过修改它来改变表单数据的编码。任何随后的属性访问（例如GET或POST）将使用新的编码方式。</p>
<h3 id="7-httprequestcontent_type">7. HttpRequest.content_type</h3>
<p>表示从<code>CONTENT_TYPE</code>头解析的请求的MIME类型。</p>
<h3 id="8-httprequestcontent_params">8. HttpRequest.content_params</h3>
<p>包含在<code>CONTENT_TYPE</code>标题中的键/值参数字典。</p>
<h3 id="9-httprequestget">9 HttpRequest.GET</h3>
<p>一个类似于字典的对象，包含GET请求中的所有参数，也就是类似http://example.com/?name=jack&amp;age=18之中的name=jack和age=18。 详情参考QueryDict文档。</p>
<h3 id="10-httprequestpost">10. HttpRequest.POST</h3>
<p>包含所有POST表单数据的键值对字典。 详情请参考QueryDict文档。 如果需要访问请求中的原始或非表单数据，可以使用<code>HttpRequest.body</code>属性。</p>
<p>注意：请使用<code>if request.method == "POST"</code>来判断一个请求是否POST类型，而不要使用<code>if request.POST</code>。</p>
<p>POST中不包含上传文件的数据。</p>
<h3 id="11-httprequestcookies">11. HttpRequest.COOKIES</h3>
<p>包含所有Cookie信息的字典。 键和值都为字符串。可以类似字典类型的方式，在cookie中读写数据，但是注意cookie是不安全的，因此，不要写敏感重要的信息。</p>
<h3 id="12-httprequestfiles">12. HttpRequest.FILES</h3>
<p>一个类似于字典的对象，包含所有上传的文件数据。 HttpRequest.FILES中的每个键为<code>&lt;input type="file" name="" /&gt;</code>中的name属性值。 HttpRequest.FILES中的每个值是一个<code>UploadedFile</code>对象。</p>
<p>要在Django中实现文件上传，就要靠这个属性！</p>
<p>如果请求方法是POST且请求的<code>&lt;form&gt;</code>中带有<code>enctype="multipart/form-data"</code>属性，那么HttpRequest.FILES将包含上传的文件的数据。 否则，FILES将为一个空的类似于字典的对象，属于被忽略、无用的情形。</p>
<h3 id="13-httprequestmeta">13. HttpRequest.META</h3>
<p>包含所有HTTP头部信息的字典。 可用的头部信息取决于客户端和服务器，下面是一些示例：</p>
<ul>
<li>CONTENT_LENGTH —— 请求正文的长度（以字符串计）。</li>
<li>CONTENT_TYPE —— 请求正文的MIME类型。</li>
<li>HTTP_ACCEPT —— 可接收的响应<code>Content-Type</code>。</li>
<li>HTTP_ACCEPT_ENCODING —— 可接收的响应编码类型。</li>
<li>HTTP_ACCEPT_LANGUAGE —— 可接收的响应语言种类。</li>
<li>HTTP_HOST —— 客服端发送的Host头部。</li>
<li>HTTP_REFERER —— Referring页面。</li>
<li>HTTP_USER_AGENT —— 客户端的<code>user-agent</code>字符串。</li>
<li>QUERY_STRING —— 查询字符串。</li>
<li>REMOTE_ADDR —— 客户端的IP地址。想要获取客户端的ip信息，就在这里！</li>
<li>REMOTE_HOST —— 客户端的主机名。</li>
<li>REMOTE_USER —— 服务器认证后的用户，如果可用。</li>
<li>REQUEST_METHOD —— 表示请求方法的字符串，例如"GET" 或"POST"。</li>
<li>SERVER_NAME —— 服务器的主机名。</li>
<li>SERVER_PORT —— 服务器的端口（字符串）。</li>
</ul>
<p>以上只是比较重要和常用的，还有很多未列出。</p>
<p>从上面可以看到，除<code>CONTENT_LENGTH</code>和<code>CONTENT_TYPE</code>之外，请求中的任何HTTP头部键转换为META键时，都会将所有字母大写并将连接符替换为下划线最后加上<code>HTTP_</code>前缀。所以，一个叫做<code>X-Bender</code>的头部将转换成META中的<code>HTTP_X_BENDER</code>键。</p>
<h3 id="13httprequestheaders">13.HttpRequest.headers</h3>
<p>一个不区分大小写、类似dict的对象，包含请求中HTTP头部的所有信息。</p>
<p>你在访问的时候，可以不区分大小写。</p>
<blockquote>
<blockquote>
<blockquote>
<p>request.headers
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}</p>
<p>'User-Agent' in request.headers
True
'user-agent' in request.headers
True</p>
<p>request.headers['User-Agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
request.headers['user-agent']
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)</p>
<p>request.headers.get('User-Agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)
request.headers.get('user-agent')
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)</p>
</blockquote>
</blockquote>
</blockquote>
<p>在模板系统中，可以通过下面的方式访问：</p>
<p>{{ request.headers.user_agent }}</p>
<h3 id="14-httprequestresolver_match">14. HttpRequest.resolver_match</h3>
<p>对请求中的URL进行解析，获取一些相关的信息，比如namespace。</p>
<p>在视图中通过request.resolver_match.namespace的方式访问。</p>
<h2 id="app">二、app带来的属性</h2>
<p>下面的属性是app带来的：</p>
<h3 id="1-httprequestcurrent_app">1. HttpRequest.current_app</h3>
<p>表示当前app的名字。url模板标签将使用它的值作为<code>reverse()</code>方法的<code>current_app</code>参数。</p>
<h3 id="2-httprequesturlconf">2. HttpRequest.urlconf</h3>
<p>设置当前请求的根<code>URLconf</code>，用于指定不同的url路由进入口，这将覆盖settings中的<code>ROOT_URLCONF</code>设置。</p>
<p>将它的值修改为None，可以恢复使用<code>ROOT_URLCONF</code>设置。</p>
<h3 id="3-httprequestexception_reporter_filter">3. HttpRequest.exception_reporter_filter</h3>
<p>用于替代当前请求的 <code>DEFAULT_EXCEPTION_REPORTER_FILTER</code> 。</p>
<h3 id="4httprequestexception_reporter_class">4.HttpRequest.exception_reporter_class</h3>
<p>用于替代当前请求的<code>DEFAULT_EXCEPTION_REPORTER</code>。</p>
<h2 id="_7">三、中间件带来的属性</h2>
<p>Django的contrib应用中包含的一些中间件会在请求上设置属性。</p>
<h3 id="1-httprequestsession">1. HttpRequest.session</h3>
<p>来自<code>SessionMiddleware</code>中间件：一个可读写的，类似字典的对象，表示当前会话。我们要保存用户状态，回话过程等等，靠的就是这个中间件和这个属性。</p>
<h3 id="2-httprequestsite">2. HttpRequest.site</h3>
<p>来自<code>CurrentSiteMiddleware</code>中间件：<code>get_current_site()</code>方法返回的Site或RequestSite的实例，代表当前站点是哪个。</p>
<p>Django是支持多站点的，如果你同时上线了几个站点，就需要为每个站点设置一个站点id。</p>
<h3 id="3-httprequestuser">3. HttpRequest.user</h3>
<p>来自<code>AuthenticationMiddleware</code>中间件：表示当前登录的用户的<code>AUTH_USER_MODEL</code>的实例，这个模型是Django内置的Auth模块下的User模型。如果用户当前未登录，则user将被设置为<code>AnonymousUser</code>的实例。</p>
<p>可以使用<code>is_authenticated</code>方法判断当前用户是否合法用户，如下所示：</p>
<p>if request.user.is_authenticated:
    ... # Do something for logged-in users.
else:
    ... # Do something for anonymous users.</p>
<h2 id="_8">四、方法</h2>
<h3 id="1-httprequestget_host">1. HttpRequest.get_host()</h3>
<p>根据<code>HTTP_X_FORWARDED_HOST</code>和<code>HTTP_HOST</code>头部信息获取请求的原始主机。 如果这两个头部没有提供相应的值，则使用<code>SERVER_NAME</code>和<code>SERVER_PORT</code>。</p>
<p>例如："127.0.0.1:8000"</p>
<p>注：当主机位于多个代理的后面，<code>get_host()</code>方法将会失败。解决办法之一是使用中间件重写代理的头部，如下面的例子：</p>
<p>class MultipleProxyMiddleware:
    FORWARDED_FOR_FIELDS = [
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED_HOST',
        'HTTP_X_FORWARDED_SERVER',
    ]</p>
<div class="language-text highlight"><pre><span></span><code>def \_\_init\_\_(self, get_response):
    self.get_response = get_response

def \_\_call\_\_(self, request):
    &quot;&quot;&quot;
</code></pre></div>
<p>Rewrites the proxy headers so that only the most
 recent proxy is used.
 """
        for field in self.FORWARDED_FOR_FIELDS:
            if field in request.META:
                if ',' in request.META[field]:
                    parts = request.META[field].split(',')
                    request.META[field] = parts[-1].strip()
        return self.get_response(request)</p>
<h3 id="2-httprequestget_port">2. HttpRequest.get_port()</h3>
<p>使用META中<code>HTTP_X_FORWARDED_PORT</code>和<code>SERVER_PORT</code>的信息返回请求的始发端口。</p>
<h3 id="3-httprequestget_full_path">3. HttpRequest.get_full_path()</h3>
<p>返回包含完整参数列表的path。例如：<code>/music/bands/the_beatles/?print=true</code></p>
<h3 id="4-httprequestbuild_absolute_urilocation">4. HttpRequest.build_absolute_uri(location)</h3>
<p>返回location的绝对URI形式。 如果location没有提供，则使用<code>request.get_full_path()</code>的值。</p>
<p>例如："https://example.com/music/bands/the_beatles/?print=true"</p>
<p>注：不鼓励在同一站点混合部署HTTP和HTTPS，如果需要将用户重定向到HTTPS，最好使用Web服务器将所有HTTP流量重定向到HTTPS。</p>
<h3 id="5-httprequestget_signed_cookiekey-defaultraise_error-salt-max_agenone">5. HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)</h3>
<p>从已签名的Cookie中获取值，如果签名不合法则返回django.core.signing.BadSignature。</p>
<p>可选参数salt用来为密码加盐，提高安全系数。 <code>max_age</code>参数用于检查Cookie对应的时间戳是否超时。</p>
<p>范例：</p>
<blockquote>
<blockquote>
<blockquote>
<p>request.get_signed_cookie('name')
'Tony'
request.get_signed_cookie('name', salt='name-salt')
'Tony' # assuming cookie was set using the same salt
request.get_signed_cookie('non-existing-cookie')
...
KeyError: 'non-existing-cookie'
request.get_signed_cookie('non-existing-cookie', False)
False
request.get_signed_cookie('cookie-that-was-tampered-with')
...
BadSignature: ...
request.get_signed_cookie('name', max_age=60)
...
SignatureExpired: Signature age 1677.3839159 &gt; 60 seconds
request.get_signed_cookie('name', False, max_age=60)
False</p>
</blockquote>
</blockquote>
</blockquote>
<h3 id="6-httprequestis_secure">6. HttpRequest.is_secure()</h3>
<p>如果使用的是Https，则返回True，表示连接是安全的。</p>
<h3 id="7-httprequestacceptsmime_type">7. HttpRequest.accepts(mime_type)</h3>
<p>Django3.1新增。</p>
<p>如果请求头部接收的类型匹配mime_type参数，则返回True，否则返回False：</p>
<blockquote>
<blockquote>
<blockquote>
<p>request.accepts('text/html')
True</p>
</blockquote>
</blockquote>
</blockquote>
<p>大多数浏览器默认的头部Accept设置是：<code>Accept: */*</code>，也就是说使用上面的accepts方法进行测试基本都会返回True。</p>
<h3 id="8-httprequestreadsizenone">8. HttpRequest.read(size=None)</h3>
<h3 id="9-httprequestreadline">9. HttpRequest.readline()</h3>
<h3 id="10-httprequestreadlines">10. HttpRequest.readlines()</h3>
<h3 id="11-httprequest__iter__">11. <code>HttpRequest.__iter__()</code></h3>
<p>上面的几个方法都是从HttpRequest实例读取文件数据的方法。</p>
<p>可以将HttpRequest实例直接传递到XML解析器，例如ElementTree：</p>
<p>import xml.etree.ElementTree as ET
for element in ET.iterparse(request):
    process(element)</p>












                
              </article>
            </div>
          
          
<script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script>
        </div>
        
      </main>
      
        <footer class="md-footer">
  
  <div class="md-footer-meta md-typeset">
    <div class="md-footer-meta__inner md-grid">
      <div class="md-copyright">
  
    <div class="md-copyright__highlight">
      Copyright 2024 Write By Heng
    </div>
  
  
</div>
      
        <div class="md-social">
  
    
    
    
    
      
      
    
    <a href="http://home.liheng.work/" target="_blank" rel="noopener" title="home.liheng.work" class="md-social__link">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc.--><path d="M244 246c-3.2-2-6.3-2.9-10.1-2.9-6.6 0-12.6 3.2-19.3 3.7l1.7 4.9zm135.9 197.9c-19 0-64.1 9.5-79.9 19.8l6.9 45.1c35.7 6.1 70.1 3.6 106-9.8-4.8-10-23.5-55.1-33-55.1zM340.8 177c6.6 2.8 11.5 9.2 22.7 22.1 2-1.4 7.5-5.2 7.5-8.6 0-4.9-11.8-13.2-13.2-23 11.2-5.7 25.2-6 37.6-8.9 68.1-16.4 116.3-52.9 146.8-116.7C548.3 29.3 554 16.1 554.6 2l-2 2.6c-28.4 50-33 63.2-81.3 100-31.9 24.4-69.2 40.2-106.6 54.6l-6.3-.3v-21.8c-19.6 1.6-19.7-14.6-31.6-23-18.7 20.6-31.6 40.8-58.9 51.1-12.7 4.8-19.6 10-25.9 21.8 34.9-16.4 91.2-13.5 98.8-10zM555.5 0l-.6 1.1-.3.9.6-.6zm-59.2 382.1c-33.9-56.9-75.3-118.4-150-115.5l-.3-6c-1.1-13.5 32.8 3.2 35.1-31l-14.4 7.2c-19.8-45.7-8.6-54.3-65.5-54.3-14.7 0-26.7 1.7-41.4 4.6 2.9 18.6 2.2 36.7-10.9 50.3l19.5 5.5c-1.7 3.2-2.9 6.3-2.9 9.8 0 21 42.8 2.9 42.8 33.6 0 18.4-36.8 60.1-54.9 60.1-8 0-53.7-50-53.4-60.1l.3-4.6 52.3-11.5c13-2.6 12.3-22.7-2.9-22.7-3.7 0-43.1 9.2-49.4 10.6-2-5.2-7.5-14.1-13.8-14.1-3.2 0-6.3 3.2-9.5 4-9.2 2.6-31 2.9-21.5 20.1L15.9 298.5c-5.5 1.1-8.9 6.3-8.9 11.8 0 6 5.5 10.9 11.5 10.9 8 0 131.3-28.4 147.4-32.2 2.6 3.2 4.6 6.3 7.8 8.6 20.1 14.4 59.8 85.9 76.4 85.9 24.1 0 58-22.4 71.3-41.9 3.2-4.3 6.9-7.5 12.4-6.9.6 13.8-31.6 34.2-33 43.7-1.4 10.2-1 35.2-.3 41.1 26.7 8.1 52-3.6 77.9-2.9 4.3-21 10.6-41.9 9.8-63.5l-.3-9.5c-1.4-34.2-10.9-38.5-34.8-58.6-1.1-1.1-2.6-2.6-3.7-4 2.2-1.4 1.1-1 4.6-1.7 88.5 0 56.3 183.6 111.5 229.9 33.1-15 72.5-27.9 103.5-47.2-29-25.6-52.6-45.7-72.7-79.9zm-196.2 46.1v27.2l11.8-3.4-2.9-23.8zm-68.7-150.4 24.1 61.2 21-13.8-31.3-50.9zm84.4 154.9 2 12.4c9-1.5 58.4-6.6 58.4-14.1 0-1.4-.6-3.2-.9-4.6-26.8 0-36.9 3.8-59.5 6.3z"/></svg>
    </a>
  
    
    
    
    
      
      
    
    <a href="https://github.com/lmliheng?tab=repositories" target="_blank" rel="noopener" title="github.com" class="md-social__link">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2024 Fonticons, Inc.--><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg>
    </a>
  
</div>
      
    </div>
  </div>
</footer>
      
    </div>
    <div class="md-dialog" data-md-component="dialog">
      <div class="md-dialog__inner md-typeset"></div>
    </div>
    
    
    <script id="__config" type="application/json">{"base": ".", "features": ["content.code.copy", "content.code.select"], "search": "assets/javascripts/workers/search.b8dbb3d2.min.js", "translations": {"clipboard.copied": "\u5df2\u590d\u5236", "clipboard.copy": "\u590d\u5236", "search.result.more.one": "\u5728\u8be5\u9875\u4e0a\u8fd8\u6709 1 \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.more.other": "\u5728\u8be5\u9875\u4e0a\u8fd8\u6709 # \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.none": "\u6ca1\u6709\u627e\u5230\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.one": "\u627e\u5230 1 \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.other": "# \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.placeholder": "\u952e\u5165\u4ee5\u5f00\u59cb\u641c\u7d22", "search.result.term.missing": "\u7f3a\u5c11", "select.version": "\u9009\u62e9\u5f53\u524d\u7248\u672c"}}</script>
    
    
      <script src="assets/javascripts/bundle.dd8806f2.min.js"></script>
      
    
  </body>
</html>